package com.hs.sfzy.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hs.sfzy.entity.Course;
import com.hs.sfzy.entity.Coursetalk;
import com.hs.sfzy.entity.User;
import com.hs.sfzy.mapper.CourseMapper;
import com.hs.sfzy.mapper.CoursereplyMapper;
import com.hs.sfzy.mapper.CoursetalkMapper;
import com.hs.sfzy.mapper.UserMapper;
import com.hs.sfzy.service.CoursetalkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * @ClassName CoursetalkServiceImpl
 * @Description TODO
 * @Author zgy
 * @Date 2024年10月25日 10:37
 * @Version 1.0
 */
@Service
public class CoursetalkServiceImpl implements CoursetalkService {
    @Autowired
    private CoursetalkMapper coursetalkMapper;
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CoursereplyMapper coursereplyMapper;

    @Override
    public int delete(Long id) {
        return coursetalkMapper.delete(id);
    }

    @Override
    public List<Coursetalk> selectAll(Coursetalk coursetalk) {
        return coursetalkMapper.selectAll(coursetalk);
    }

    @Override
    public Coursetalk selectById(Long id) {
        return coursetalkMapper.selectById(id);
    }

    @Override
    public PageInfo<Coursetalk> selectByPageInfo(int pageNum, int pageSize, Coursetalk coursetalk) {
        PageHelper.startPage(pageNum,pageSize);
        List<Coursetalk> list = coursetalkMapper.selectAll(coursetalk);
        for (Coursetalk ct : list){
            Long courseId = ct.getCourseId();
            Long userId = ct.getUserId();
            Course course = courseMapper.selectById(courseId);
            User user = userMapper.getUserById(userId);
            ct.setCourse(course);
            ct.setUser(user);
        }
        PageInfo<Coursetalk> pageInfo = new PageInfo<Coursetalk>(list);
        return pageInfo;
    }

    @Override
    public List<Coursetalk> selectByCourseId(Long courseId) {
        List<Coursetalk> coursetalks = coursetalkMapper.selectByCourseId(courseId);
        for (Coursetalk ct : coursetalks){
            Long userId = ct.getUserId();
            Course course = courseMapper.selectById(courseId);
            User user = userMapper.getUserById(userId);
            // 获取关联的课程
            ct.setCourse(course);
            // 获取提出问题的user
            ct.setUser(user);
            // 获取该问题下有几条回复
            ct.setCoursereplycount(coursereplyMapper.countReplyByTalk(ct.getId()));
            // 获取该问题下的回复集合
            ct.setCoursereply(coursereplyMapper.selectByTalkId(ct.getId()));
        }
        return coursetalks;
    }

    @Override
    public int insert(Coursetalk coursetalk) {
        int insert = coursetalkMapper.insert(coursetalk);
        return insert;
    }
}
